<template>
  <vxe-modal
    ref="modal"
    :title="title"
    :width="width"
    v-model="dialogVisible"
    v-bind="$attrs"
    :before-hide-method="clear"
    :destroy-on-close="true"
    @toggle-row-expand="resetModal"
    @toggle-tree-expand="resetModal"
  >
    <vxe-form v-if="searchConfig && searchConfig.length > 0" :data="form" title-align="right">
      <vxe-form-item v-for="item in searchConfig" :key="item.label" :title="item.label" :item-render="{}">
        <template #default="{ data }">
          <vxe-input v-model="data[item.field]" class="normal" :placeholder="item.label" clearable></vxe-input>
        </template>
      </vxe-form-item>
      <vxe-form-item title="" field="" :item-render="{}">
        <template>
          <vxe-button status="primary" icon="vxe-icon-search" size="small" title="搜索" @click="search"></vxe-button>
          <vxe-button status="info" icon="vxe-icon-indicator" size="small" title="重置" @click="reset"></vxe-button>
        </template>
      </vxe-form-item>
    </vxe-form>
    <vxe-grid
      :class="[border === 'inner' ? 'table-normal' : '']"
      ref="table"
      resizable
      maxHeight="400"
      show-overflow
      :key="Date.now()"
      keep-source
      size="small"
      :border="border"
      :data="transformTableData"
      :columns="columns"
      :row-config="{ keyField: 'id', useKey: true }"
      :span-method="rowspanMethod"
      v-bind="selectConfig"
      @checkbox-change="changeSelect"
      @checkbox-all="changeSelect"
    >
    </vxe-grid>
    <vxe-pager
      background
      :current-page.sync="form.page"
      :page-size.sync="form.pageSize"
      :total="total"
      :layouts="['Total', 'Sizes', 'PrevPage', 'JumpNumber', 'NextPage']"
      @page-change="change"
    >
    </vxe-pager>
    <div slots="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submit">{{ submitBtn }}</el-button>
    </div>
  </vxe-modal>
</template>
<script>
import VXETable from 'vxe-table';
export default {
  props: {
    title: {
      type: String,
      default: '',
    },
    width: {
      type: String,
      default: '80%',
    },
    columns: {
      type: Array,
      default: () => [],
    },
    tableData: {
      type: Array,
      default: () => [],
    },
    total: {
      type: [String, Number],
      default: 0,
    },
    type: {
      type: String,
      default: 'checkbox',
    },
    searchConfig: {
      type: Array,
      default: () => [],
    },
    value: {
      type: Array,
      default: () => [],
    },
    submitBtn: {
      type: String,
      default: '确 定',
    },
    border: {
      type: String,
      default: 'inner',
    },
  },
  data() {
    return {
      dialogVisible: false,
      form: {
        page: 1,
        size: 10,
      },
      result: [],
    };
  },
  mounted(){
    // console.log('123',searchConfig);
  },
  watch: {
    dialogVisible(val) {
      this.result = [...this.value];
      this.resetModal();
    },
  },
  computed: {
    transformTableData() {
      return this.tableData.map((item, i) => {
        return {
          ...item,
          id: item.id || item.sampleId,
        };
      });
    },
    checkRowids() {
      return this.result?.map((item) => item.id);
    },
    selectConfig() {
      return this.columns[0]?.type === 'radio'
        ? { 'radio-config': { trigger: 'row' } }
        : { 'checkbox-config': { trigger: 'row', checkRowKeys: this.checkRowids } };
    },
  },
  methods: {
    search() {
      this.form.page = 1;
      this.$emit('search', this.form);
    },
    reset() {
      this.resetPage();
      this.$emit('search', this.form);
    },
    clear() {
      this.$refs.table.clearCheckboxRow();
      this.dialogVisible = false;
      this.reset();
    },
    cancel() {
      this.dialogVisible = false;
      this.reset();
    },
    changeSelect(data) {
      const records = data.records;
      if (records.every((item) => item.id !== data.row.id)) {
        this.result = this.result.filter((item) => item.id !== data.row.id);
      } else {
        // 去重
        this.result = [...this.result, ...records.filter((item) => this.result.every((it) => it.id !== item.id))];
      }
    },
    submit() {
      const result = this.type === 'checkbox' ? this.result : this.$refs.table.getRadioRecord();
      if (!result || result.length === 0) {
        VXETable.modal.message({
          content: '未有选中项',
          status: 'error',
        });
        return;
      }
      this.$emit('submit', result);
      this.clear();
    },
    change({ type, currentPage, pageSize }) {
      this.form.page = currentPage;
      this.form.size = pageSize;
      this.$emit('pager', this.form);
    },
    // 重置参数
    resetPage() {
      this.form = {
        page: 1,
        size: 10,
      };
    },
    resetModal() {
      this.$refs.modal.setPosition('center', 'center');
    },
    rowspanMethod({ row, _rowIndex, column, visibleData }) {
      let fields = ['checkbox', 'reportNumber', 'entrustNumber', 'itemName'];
      let cellValue = row[column.property];
      if (cellValue && fields.includes(column.property)) {
        let prevRow = visibleData[_rowIndex - 1];
        let nextRow = visibleData[_rowIndex + 1];
        if (prevRow && prevRow[column.property] + '' + prevRow.id === cellValue + '' + row.id) {
          return { rowspan: 0, colspan: 0 };
        } else {
          let countRowspan = 1;
          while (nextRow && nextRow[column.property] + '' + nextRow.id === cellValue + '' + row.id) {
            nextRow = visibleData[++countRowspan + _rowIndex];
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 };
          }
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep {
  .table-normal .vxe-body--row .vxe-body--column {
    height: 40px !important;
  }
  .vxe-table--body-wrapper {
    overflow: auto !important;
  }
  .vxe-modal--box {
    position: absolute;
    left: 50% !important;
    top: 50% !important;
    transform: translate(-50%, -50%) !important;
  }
}
</style>
